<template>
	<view class="switchAddress">
		<!-- 该组件，主要监听地址切换，更改地址 -->
		<view class="btn df-aic-jucen">{{address|addrHide}}</view>
	</view>
</template>

<script>
	import {istest} from "@/utils/common.js";
	import detectEthereumProvider from "@metamask/detect-provider";
	import { ethers } from 'ethers'
	import BigNumber from 'bignumber.js'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		computed: {
			...mapState(['address']),
		},
		data() {
			return {
				switchAdd:false,
			}
		},
		async mounted() {
			// console.log('头部组件');
			if (typeof window.ethereum !== "undefined") {
				await this.getWeb3Init()
				await this.switchEthereumChain()
				var provider = await detectEthereumProvider();
				provider.on("accountsChanged", (accounts) => {
					this.$store.commit("setAddress", accounts[0])
					window.location.reload()
				});
			}
		},
		methods: {
			// 初始化
			async getWeb3Init(){
				this.erc20 = await this.$dapp.erc20.init('USDT');
				console.log('导航组件更新地址：',this.erc20.account);
				this.$store.commit("setAddress", this.erc20.account)
				uni.setStorageSync('address', this.erc20.account);
			},
			// 检查网络链接
			async switchEthereumChain() {
				try {
					let id = 0
					if(istest){
						id = 56
					}else{
						id = 97
					}
					await window.ethereum.request({
						method: 'wallet_switchEthereumChain',
						params: [{
							chainId: ethers.utils.hexlify(id) // 目标链ID
						}]
					})
				} catch (e) {
					// console.log('没有切换成功，并且e.code == 4902，则添加56');
					if (e.code == 4902) { //添加链
						await window.ethereum.request({
							method: 'wallet_addEthereumChain',
							params: [{
								chainId: '0x38',
								chainName: 'BSC',
								nativeCurrency: {
									name: 'BNB',
									symbol: 'BNB',
									decimals: 18,
								},
								rpcUrls: ['https://bsc-dataseed.binance.org/'],
								blockExplorerUrls: ['https://bscscan.com/'],
							}, ],
						})
					} else {
						this.$toast(e.message)
						throw e
					}
				}
			},

		}
	}
</script>

<style scoped lang="scss">
	.switchAddress {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		.btn{
			padding: 0 30rpx;
			height: 60rpx;
			background: #77FF4B;
			border-radius: 10rpx;
			font-size: 24rpx;
			color: #000;
			font-weight: bold;
		}
	}
</style>